import { IMouseMoveEvent, IMovement } from '@/types/utils'
import { uuidv4 } from '@/utils/uuidv4'
import { watchEffect } from 'vue'
import { markRaw, ref, shallowRef } from 'vue'
import { useTurf } from '..'
import { bbox, lineString } from '@turf/turf'
import { ShadowMode } from 'cesium'
interface IOverlay {
    positions: number[][]
    thumbnail: string
    id: string
}

type IOverlayLoaded = IOverlay & {
    plygonEntity: Cesium.Entity | null
    imageEntity: Cesium.Entity | null
}

function useCesiumPolygon() {
    const viewer = shallowRef<Cesium.Viewer>()

    const PolygonSourceKey = 'polygon_source'

    const PolygonImageSourceKey = 'polygon_image_source'

    const plySource = shallowRef(new Cesium.CustomDataSource(PolygonSourceKey))

    const imgSource = shallowRef(
        new Cesium.CustomDataSource(PolygonImageSourceKey),
    )

    const overlayPolygonList = shallowRef<IOverlayLoaded[]>([])

    const overlayImgList = shallowRef<IOverlayLoaded[]>([])

    // 处理鼠标移入移出事件
    function mouseInOut(movement: IMouseMoveEvent) {
        // 鼠标移动

        // console.log('movement======>', movement)

        const { endPosition, startPosition } = movement

        const pickedObject = viewer.value?.scene.pick(endPosition)

        // 如果找到对象了
        if (pickedObject) {
            const entity = pickedObject.id as Cesium.Entity

            if (Cesium.defined(pickedObject) && entity) {
                // console.log('存在实体entity', entity)

                // 查找 是否在

                const plyItem = overlayPolygonList.value.find((item) => {
                    return item.id == entity.id
                })

                // 如果找到对应的多边形
                if (plyItem) {
                    // console.log('plyItem======>', plyItem)

                    const { plygonEntity, imageEntity } = plyItem

                    if (plygonEntity) {
                        plySource.value.entities.contains(plygonEntity)

                        // imgSource.value.entities

                        // plygonEntity.show = true
                        // // imageEntity?.show
                    }

                    // 如果在其中已经有 贴图了
                    if (imageEntity) {
                        // 查看是否贴到地图上了
                        const hasLoaded =
                            imgSource.value.entities.contains(imageEntity)

                        // 如果没贴上,贴上该图片
                        if (!hasLoaded) {
                            // 清空地图上别的贴图实体
                            clearOverlayImg()
                            // 将该缩略图实体贴到地图上
                            imgSource.value.entities.add(imageEntity)
                        }
                        imageEntity.show = true
                    }
                }
            }
            // 如果没找到对象
        } else {
            // console.log('不存在此实体')
            // 将地图上的所有缩略图清空
            // clearOverlayImg()

            overlayPolygonList.value.forEach((item) => {
                const { imageEntity } = item

                if (imageEntity) {
                    imageEntity.show = false
                }
            })

            return console.warn('pickedObject', pickedObject)
        }
    }

    function pickEntityFromViewer(movement: IMovement, viewer: Cesium.Viewer) {
        const pickedObject = viewer!.scene.pick(movement.position)

        if (!pickedObject) return console.warn('pickedObject', pickedObject)

        const entity: Cesium.Entity = pickedObject.id

        // handleClickContextOutside()

        if (Cesium.defined(pickedObject) && entity) {
            // onEntityClick(entity)

            return entity
        } else {
            null
        }
    }

    let polygonClickFn: (entity: Cesium.Entity) => void
    function onPolygonClick(fn?: (entity: Cesium.Entity) => void) {
        if (fn) {
            return (polygonClickFn = fn)
        }
    }

    function overlayClick(movement: IMovement) {
        console.log('overlayClick item :>> ', movement)
        const entity = pickEntityFromViewer(movement, viewer.value!)

        if (!entity) {
            return console.warn('pickedObject', entity)
        } else {
            return polygonClickFn && polygonClickFn(entity)
        }
    }

    function initEvent() {
        const handler = new Cesium.ScreenSpaceEventHandler(
            viewer.value!.scene.canvas,
        )

        // 鼠标移入移出
        handler.setInputAction(
            mouseInOut,
            Cesium.ScreenSpaceEventType.MOUSE_MOVE,
        )

        handler.setInputAction(
            overlayClick,
            Cesium.ScreenSpaceEventType.LEFT_CLICK,
        )
    }

    function clearOverlayImg() {
        overlayImgList.value = []

        imgSource.value.entities.removeAll()
    }

    function clearOverlayPolygon() {
        overlayPolygonList.value = []

        plySource.value.entities.removeAll()
    }

    function init(_viewer: Cesium.Viewer) {
        viewer.value = _viewer!

        viewer.value.dataSources.add(plySource.value)
        viewer.value.dataSources.add(imgSource.value)
        initEvent()
    }

    function addPolygon(overlayInfo: IOverlay) {
        let polygonPositions: Cesium.Cartesian3[] = []

        const { id, positions, thumbnail } = overlayInfo

        // console.log('positions======>', positions);

        // turf 缩放
        // const scalePly = turf.transformScale(turf.polygon([positions]), 1.2)

        // polygonPositions = scalePly.geometry.coordinates[0].map((pos) => {
        polygonPositions = positions.map((pos) => {
            return Cesium.Cartesian3.fromDegrees(pos[0], pos[1])
        })

        const polygonHierarchy = new Cesium.PolygonHierarchy(
            polygonPositions,
            [],
        )

        const polygonGraphics = new Cesium.PolygonGraphics({
            hierarchy: polygonHierarchy,
            material: Cesium.Color.ORANGE.withAlpha(0.6),
            outlineColor: Cesium.Color.WHITE.withAlpha(0.4),
            outlineWidth: 5,
            // shadows: ShadowMode.CAST_ONLY,
            height: 0,
            outline: true,
            // fill:false,
        })

        const params: Cesium.Entity.ConstructorOptions = id
            ? {
                  id,
                  polygon: polygonGraphics,
              }
            : { polygon: polygonGraphics }

        const ply = plySource.value.entities.add(params)

        const meterial = new Cesium.ImageMaterialProperty({
            image: thumbnail,
            transparent: true,
        })

        const img = new Cesium.Entity({
            id: `${id}_img`,
            name: `${id}_img`,
            
            polygon: {
                hierarchy: new Cesium.PolygonHierarchy(polygonPositions),
                outlineColor: Cesium.Color.WHITE.withAlpha(0.4),
                outlineWidth: 40,
                height: 0,
                perPositionHeight: true,
                extrudedHeight: 0,
                outline: true,
                // outlineWidth:5,
                // fill:false,
                // material: new Cesium.MaterialProperty(''),
                // material: thumbnail,
                material: meterial,
                show: true,
            },
        })

        imgSource.value.entities.add(img)

        overlayPolygonList.value.push({
            id,
            plygonEntity: ply,
            imageEntity: img,
            positions,
            thumbnail: thumbnail,
        })

        return ply
    }
    function addPolygonOverlay(postions: number[][], id?: string) {
        let polygonPositions: Cesium.Cartesian3[] = []

        polygonPositions = postions.map((pos) => {
            return Cesium.Cartesian3.fromDegrees(pos[0], pos[1])
        })

        const polygonHierarchy = new Cesium.PolygonHierarchy(
            polygonPositions,
            [],
        )

        const polygonGraphics = new Cesium.PolygonGraphics({
            hierarchy: polygonHierarchy,
            material: Cesium.Color.ORANGE.withAlpha(0.2),
            outlineColor: Cesium.Color.WHITE.withAlpha(0.4),
            outlineWidth: 5,

            height: 0,
            outline: true,
        })

        const params: Cesium.Entity.ConstructorOptions = id
            ? {
                  id,
                  polygon: polygonGraphics,
              }
            : { polygon: polygonGraphics }

        const ply = viewer.value!.entities.add(params)

        return ply
    }

    function removePolygon() {}

    function addPolygonImg() {}

    function removePolygonImg() {}

    function flyToPolygon(
        polygonCoordinates: {
            lon: number
            lat: number
        }[],
    ) {
        const polygonPositions = polygonCoordinates.map((coord) =>
            Cesium.Cartographic.fromDegrees(coord.lon, coord.lat),
        )

        const boundingRectangle =
            Cesium.Rectangle.fromCartographicArray(polygonPositions)

        viewer.value?.camera.flyTo({
            destination: boundingRectangle,
            duration: 1,
        })
    }

    function isImgPolygon(entity: Cesium.Entity) {
        return entity.id.endsWith('_img')
    }

    return {
        customeDataSource: plySource,
        overlayPolygonList,
        overlayImgList,
        mouseInOut,
        initEvent,
        clearOverlayImg,
        clearOverlayPolygon,
        init,
        addPolygon,
        flyToPolygon,
        onPolygonClick,
        isImgPolygon,
    }
}

export default useCesiumPolygon
